package com.ulife.permission.module.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.form.Group;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.dataresolver.FormGroup;
import com.alibaba.citrus.webx.WebxException;
import com.ulife.common.GroupUtils;
import com.ulife.common.Result;
import com.ulife.common.WebConstant;
import com.ulife.common.exception.ManagerException;
import com.ulife.permission.common.SysUser;
import com.ulife.permission.dao.dataobject.DepartmentDO;
import com.ulife.permission.dao.dataobject.UserDO;
import com.ulife.permission.exceptions.DepartmentErrorException;
import com.ulife.permission.manager.DepartmentManager;
import com.ulife.permission.manager.UserManager;

public class UserAction {

	private static final Logger log = LoggerFactory.getLogger(UserAction.class);
	
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private UserManager userManager;
	@Autowired
	private DepartmentManager departmentManager;
	
	/**
	 * 新增用户
	 * @param group
	 * @param context
	 * @param nav
	 * @throws WebxException
	 */
	public void doAddUser(@FormGroup("adduser") Group group, Context context, Navigator nav) throws WebxException {
		GroupUtils groupUtil = new GroupUtils(group);
		try {
			UserDO user = new UserDO();
			setUser(user, groupUtil);
			user.setStatus(0);
			Result<UserDO> result = userManager.addUser(user);
			if (result == null || !result.isSuccess() || null == result.getModule()) {
				context.put("error", "系统错误");
				return;
			}
		}
		catch (DepartmentErrorException e) {
			log.error("add user error", e);
		}
		catch (ManagerException e) {
			context.put("error", "系统错误");
			log.error("add user error", e);
		}
		
	}
	
	/**
	 * 删除用户
	 * @param group
	 * @param context
	 * @param nav
	 * @throws WebxException
	 */
	public void doDelUser(@FormGroup("deluser") Group group, Context context, Navigator nav) throws WebxException {
		GroupUtils groupUtil = new GroupUtils(group);
		long userId = groupUtil.getLong("userId");
		int status = groupUtil.getInt("status");
		try {
			if (status < 0 || status > 1) {
				context.put("error", "系统错误");
				return;
			}
			if (userId >= 0) {
				Result<UserDO> userResult = userManager.getUserById(userId);
				if (userResult != null && userResult.isSuccess() && userResult.getModule() != null) {
					UserDO user = userResult.getModule();
					if (StringUtils.equals(user.getRoleIdList(), "admin")) {
						context.put("error", "管理员不能被删除");
						return;
					}
					if (user.getStatus() != status) {
						user.setStatus(status);
						Result<Integer> result = userManager.updateUser(user);
						if (result == null || !result.isSuccess()) {
							context.put("error", "系统错误");
							return;
						}
					}
				}
				else {
					context.put("error", "系统错误");
					return;
				}
			}
		}
		catch (Exception e) {
			context.put("error", "系统错误");
			log.error("del user error, user id = " + userId, e);
		}
	}
	
	/**
	 * 编辑用户
	 * @param group
	 * @param context
	 * @param nav
	 * @throws WebxException
	 */
	public void doUpdateUser(@FormGroup("updateuser") Group group, Context context, Navigator nav) throws WebxException {
		GroupUtils groupUtil = new GroupUtils(group);
		long userId = groupUtil.getLong("userId");
		try {
			
			if (userId >= 0) {
				Result<UserDO> userResult = userManager.getUserById(userId);
				if (userResult != null && userResult.isSuccess() && userResult.getModule() != null) {
					UserDO user = userResult.getModule();
					if (StringUtils.equals(user.getRoleIdList(), "admin")) {
						context.put("error", "管理员不能被编辑");
						return;
					}
					setUser(user, groupUtil);
					Result<Integer> updateResult = userManager.updateUser(user);
					if (updateResult == null || !updateResult.isSuccess()) {
						log.error("update user error, user id = " + userId);
						context.put("error", "更新错误");
						return;
					}
				}
			}else {
				context.put("error", "系统错误");
				log.error("update user error, user id = " + userId);
			}
		} 
		catch (DepartmentErrorException e) {
			log.error("update user error, user id = " + userId, e);
		}
		catch (ManagerException e) {
			context.put("error", "系统错误");
			log.error("update user error, user id = " + userId, e);
		}
	}
	
	private void setUser(UserDO user, GroupUtils group) throws ManagerException {
		String userName = group.getString("userName");
		String realName = group.getString("realName");
		String password = group.getString("password");
		String mobilePhone = group.getString("mobilePhone");
		String telephone = group.getString("telephone");
		String eMail = group.getString("eMail");
		String departmentIdStr = group.getString("department");
		String note = group.getString("note");
		
		DepartmentDO department = null;
		if (StringUtils.isNotBlank(departmentIdStr) && StringUtils.isNumeric(departmentIdStr)) {
			long departmentId = Long.parseLong(departmentIdStr);
			Result<DepartmentDO> dResult = departmentManager.getDepartmentById(departmentId);
			if (dResult != null && dResult.isSuccess() && dResult.getModule() != null) {
				department = dResult.getModule();
			}
			else {
				group.setMessage("department", "invalidDepartment");
				throw new DepartmentErrorException("department id error: " + departmentIdStr);
			}
		}
		
		if (StringUtils.isNotBlank(userName)) {
			user.setUserName(userName);
		}
		if (StringUtils.isNotBlank(realName)) {
			user.setRealName(realName);
		}
		if (StringUtils.isNotBlank(password)) {
			user.setPassword(password);
		}
		if (StringUtils.isNotBlank(mobilePhone)) {
			user.setMobilePhone(mobilePhone);
		}
		if (StringUtils.isNotBlank(telephone)) {
			user.setTelephone(telephone);
		}
		if (StringUtils.isNotBlank(eMail)) {
			user.seteMail(eMail);
		}
		if (department != null) {
			user.setDepartment(department.getDepartmentName());
			user.setDepartmentId(department.getDepartmentId());
			user.setRoleIdList(department.getRoleList());
			user.setRoleNameList(department.getRoleNameList());
		}
		if (StringUtils.isNotBlank(note)) {
			user.setNote(note);
		}
	}
	
	/**
	 * 配置角色
	 * @param context
	 * @param nav
	 * @throws WebxException
	 */
	public void doEditUser(Context context, Navigator nav) throws WebxException {
		String userIdStr = request.getParameter("userId");
		String[] roles = request.getParameterValues("role");
		if (StringUtils.isNotBlank(userIdStr)) {
			try {
				long userId = Long.parseLong(userIdStr);
				Result<UserDO> result = userManager.getUserById(userId);
				if (result != null && result.isSuccess() && null != result.getModule()) {
					UserDO user = result.getModule();
					if (!StringUtils.equals(user.getRoleIdList(), "admin")) {
						List<String> rIdList = new ArrayList<String>();
						List<String> rNameList = new ArrayList<String>();
						for (String role : roles) {
							String[] rs = StringUtils.split(role, ":");
							rIdList.add(rs[0]);
							rNameList.add(rs[1]);
						}
						String roleList = StringUtils.join(rIdList, ",");
						String roleNameList = StringUtils.join(rNameList, ",");
						user.setRoleIdList(roleList);
						user.setRoleNameList(roleNameList);
						Result<Integer> roleResult = userManager.updateUser(user);
						if (roleResult == null || !roleResult.isSuccess()) {
							context.put("msg", "更新用户角色信息错误");
						}
						else {
							context.put("msg", "保存成功");
						}
					}
				}
			} 
			catch (ManagerException e) {
				context.put("msg", "系统错误");
				log.error("Authorization role error", e);
			}
		}
		else {
			context.put("msg", "更新用户角色信息错误");
		}
	}

	/**
	 * 用户自己修改密码
	 * @param group
	 * @param context
	 * @param nav
	 * @throws WebxException
	 */
	public void doModifyPassword(@FormGroup("modifypassword") Group group, Context context, Navigator nav) throws WebxException {
		GroupUtils groupUtil = new GroupUtils(group);
		String oldPassword = groupUtil.getString("oldPassword");
		String newPassword = groupUtil.getString("newPassword");
		String checkNewPassword = groupUtil.getString("checkNewPassword");
		if (!StringUtils.equals(newPassword, checkNewPassword)) {
			groupUtil.setMessage("newPasswordError", "invalidNewPassword");
			return;
		}
		SysUser sysUser = (SysUser) request.getSession().getAttribute(WebConstant.SYS_USER_SESSION_KEY);
		long userId = sysUser.getId();
		try {
			Result<UserDO> userResult = userManager.getUserById(userId);
			if (null != userResult && userResult.isSuccess() && userResult.getModule() != null) {
				UserDO user = userResult.getModule();
				if (!StringUtils.equals(oldPassword, user.getPassword())) {
					groupUtil.setMessage("oldPasswordError", "invalidOldPassword");
					return;
				}
				user.setPassword(newPassword);
				Result<Integer> result = userManager.updateUser(user);
				if (result != null && result.isSuccess()) {
					context.put("success", true);
				} 
				else {
					context.put("error", "系统错误");
					log.error("查询用户失败，user id = " + userId);
				}
			}
			else {
				context.put("error", "系统错误");
				log.error("查询用户失败，user id = " + userId);
			}
		} catch (ManagerException e) {
			context.put("error", "系统错误");
			log.error("查询用户失败，user id = " + userId, e);
		}
	}
	
}
